package com.zzyl.service.impl;
import cn.hutool.core.bean.BeanUtil;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.ResourceDto;
import com.zzyl.entity.Resource;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.service.ResourceService;
import com.zzyl.utils.EmptyUtil;
import com.zzyl.utils.NoProcessing;
import com.zzyl.utils.StringUtils;
import com.zzyl.vo.ResourceVo;
import com.zzyl.vo.TreeItemVo;
import com.zzyl.vo.TreeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

@Service
public class ResourceServiceImpl implements ResourceService {
    @Autowired
    private ResourceMapper resourceMapper;



    @Override
    @Cacheable(value = "resourceList",key ="#resourceDto.hashCode()")
    public List<ResourceVo> findResourceList(ResourceDto resourceDto) {
//        Resource resource = BeanUtil.toBean(resourceDto, Resource.class);
        return resourceMapper.findResourceList(resourceDto);
    }

    @Override
    @Cacheable(value = "resourceTree",key ="#resourceDto.hashCode()")
    public TreeVo resourceTreeVo(ResourceDto resourceDto) {
//        查询出所有
        List<ResourceVo> resourceList = resourceMapper.findResourceList(resourceDto);
        TreeVo treeVo = TreeVo.builder().items(new ArrayList<>()).build();
//        创建根部
        TreeItemVo rootItemVo = TreeItemVo.builder().id(SuperConstant.ROOT_PARENT_ID  ).label("智慧养老院").children(new ArrayList<>()).build();
        treeVo.getItems().add(rootItemVo);
//        递归构建树形
        recursionTreeItem(rootItemVo,resourceList);
        return  treeVo;
    }
    private void recursionTreeItem(TreeItemVo rootItemVo, List<ResourceVo> resourceList) {
          //iter 快捷生成循环·
        for (ResourceVo vo : resourceList) {
            if (rootItemVo.getId().equals(vo.getParentResourceNo()) && vo.getResourceType().equals(SuperConstant.MENU)
            ){
               TreeItemVo itemVo= TreeItemVo.builder().id(vo.getResourceNo()).label(vo.getResourceName()).children(new ArrayList<>()).build();
                  rootItemVo.getChildren().add(itemVo);
                  recursionTreeItem(itemVo,resourceList);
            }
        }
    }
    @Override  //新增的资源数据的状态要与父级资源的状态保持一致，所以，需要查询父级菜单的状态，需单独定义mapper查询
    //在ResourceMapper中新增查询方法
//    @CacheEvict(value ="resourceTree",allEntries = true )//不支持同时删除两个  但是cacheing支持
    @Caching(evict = {@CacheEvict(value ="resourceTree",allEntries = true ),
                      @CacheEvict(value ="resourceList",allEntries = true )})
    public void createResource(ResourceDto resourceDto) {
        Resource resource = BeanUtil.toBean(resourceDto, Resource.class);
      //查询父资源状态  根据传来的resourceDto 获取父类id 通过id 获取状态
        Resource parenetResource = resourceMapper.selectByResourceNo(resourceDto.getParentResourceNo());
        //给新增资源赋值状态
        resource.setDataState(parenetResource.getDataState());

        boolean isIgonre=true;
        if (StringUtils.isNotEmpty(resourceDto.getResourceType()) &&
                resourceDto.getResourceType().equals(SuperConstant.BUTTON)
        ) {
            isIgonre=false;
         }
        //创建新增的资源编号
        String resourceNo = createResourceNo(resourceDto.getParentResourceNo(), isIgonre);//isIgnore
        resource.setResourceNo(resourceNo);
        resourceMapper.insert(resource);
    }
    /**
     * 创建资源的编号
     * @param parentResourceNo
     * @return
     */
    private String createResourceNo(String parentResourceNo,boolean isIgnore) {

        //判断资源编号是否大于三级
        //100 001 000 000 000
        //100 001 001 000 000
        //100 001 001 001 000
        //100 001 001 001 001 001
        if(isIgnore && NoProcessing.processString(parentResourceNo).length() / 3 >= 5){
            throw new BaseException(BasicEnum.RESOURCE_DEPTH_UPPER_LIMIT);
        }

        //根据父资源编号查询子资源
        ResourceDto dto = ResourceDto.builder().parentResourceNo(parentResourceNo).build();

        List<ResourceVo> resources = resourceMapper.findResourceList(dto);
        if(EmptyUtil.isNullOrEmpty(resources)){
            //无下属节点，创建新的节点编号  100 001 001 001 000--->100 001 001 001 001
            return NoProcessing.createNo(parentResourceNo,false);
        }else {
            //有下属节点，在已有的节点上追加
            //先获取已有节点的最大值--100001003000000
            Long maxNo = resources.stream().map(resource -> {
                return Long.valueOf(resource.getResourceNo());
            }).max(Comparator.comparing(i -> i)).get();

            return NoProcessing.createNo(String.valueOf(maxNo),true);
        }
    }
    @Override
    public void deleteByPrimaryKey(ResourceDto resourceDto) {
        
    }
}
